/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.je.common.base.DynaBean;
import com.je.common.base.constants.dd.DDType;
import com.je.common.base.constants.tree.NodeType;
import com.je.common.base.entity.QueryInfo;
import com.je.common.base.exception.PlatformException;
import com.je.common.base.exception.PlatformExceptionEnum;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.rpc.SystemVariableRpcService;
import com.je.common.base.util.StringUtil;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.meta.model.SQLTreeNodeType;
import com.je.meta.service.MetaDictionaryItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @program: jecloud-meta
 * @author: LIULJ
 * @create: 2021-09-17 13:44
 * @description: SQLTREE字典项服务实现
 */
@Service("metaSqlTreeDictionaryItemService")
public class MetaSqlTreeDictionaryItemServiceImpl implements MetaDictionaryItemService {

    @Autowired
    private MetaService metaService;
    @Autowired
    private SystemVariableRpcService systemVariableRpcService;

    @Override
    public List<JSONTreeNode> getDdItems(DynaBean dictionary, Map<String, String> params, QueryInfo queryInfo, Boolean en) {
        if (dictionary == null) {
            throw new PlatformException("获取字典为空！", PlatformExceptionEnum.UNKOWN_ERROR);
        }
        //非列表字典抛出异常
        if (!DDType.SQL_TREE.equals(dictionary.getStr("DICTIONARY_DDTYPE"))) {
            throw new PlatformException("获取字典项异常，非法的字典类型" + dictionary.getStr("DICTIONARY_DDTYPE"), PlatformExceptionEnum.UNKOWN_ERROR);
        }

        //声明变量集合，用于解析whereSql的通配符
        Map<String, Object> ddMap = systemVariableRpcService.formatCurrentUserAndCachedVariables();
        if (params != null) {
            ddMap.putAll(params);
        }

        String querySql = StringUtil.getDefaultValue(queryInfo.getWhereSql(), "");
        String ddWhereSql = dictionary.getStr("DICTIONARY_WHERESQL", "");
        if (StringUtil.isNotEmpty(querySql)) {
            querySql = StringUtil.parseKeyWord(querySql, ddMap);
        }

        String sql = dictionary.getStr("DICTIONARY_SQL");
        if (StringUtil.isNotEmpty(ddWhereSql)) {
            querySql += ddWhereSql;
        }
        String sqlConfig = dictionary.getStr("DICTIONARY_SQLCONFIG");
        if (StringUtil.isEmpty(sql) && StringUtil.isEmpty(sqlConfig)) {
            throw new PlatformException("SQL树形字典配置错误！", PlatformExceptionEnum.UNKOWN_ERROR);
        }

        sql = StringUtil.parseKeyWord(sql, ddMap);
        if (StringUtil.isNotEmpty(querySql)) {
            querySql = StringUtil.parseKeyWord(querySql, ddMap);
            sql += querySql;
        }
        List<Map<String, Object>> values = metaService.selectSql(sql);
//        List<Map> sqlConfigMap = JsonBuilder.getInstance().fromJsonArray(sqlConfig);
        List<JSONTreeNode> lists = new ArrayList();
        JSONTreeNode node;
        JSONObject config = (JSONObject) JSON.parse(sqlConfig);
        for (Map map : values) {
            for (String code : config.keySet()) {
                String fieldType = code;
                String fieldName = config.getString(code);
                node = new JSONTreeNode();
                String value = map.get(fieldName).toString();
                if (StringUtil.isNotEmpty(fieldName)) {
                    if (SQLTreeNodeType.ID.equals(fieldType)) {
                        node.setId(value);
                    } else if (SQLTreeNodeType.NAME.equals(fieldType)) {
                        node.setText(value);
                    } else if (SQLTreeNodeType.CODE.equals(fieldType)) {
                        node.setCode(value);
                    } else if (SQLTreeNodeType.PARENT.equals(fieldType)) {
                        node.setParent(value);
                    } else if (SQLTreeNodeType.NODETYPE.equals(fieldType)) {
                        node.setNodeType(value);
                        node.setLeaf(NodeType.LEAF.equals(value));
//                } else if (SQLTreeNodeType.NODEINFO.equals(fieldType)) {
//                    node.setNodeInfo(value);
//                } else if (SQLTreeNodeType.NODETYPE.toString().equals(fieldType)) {
//                    node.setNodeInfoType(value);
                    } else if (SQLTreeNodeType.PATH.equals(fieldType)) {
                        node.setNodePath(value);
                    } else if (SQLTreeNodeType.DISABLED.equals(fieldType)) {
                        node.setDisabled(value);
                    } else if (SQLTreeNodeType.TREEORDERINDEX.equals(fieldType)) {
                        if (StringUtil.isNotEmpty(value)) {
                            node.setOrderIndex(value);
                        } else {
                            node.setOrderIndex("0");
                        }
                    } else if (SQLTreeNodeType.ICONCLS.equals(fieldType)) {
                        node.setIcon(value);
//                } else if (SQLTreeNodeType.ICONCOLOR.toString().equals(fieldType)) {
//                    node.setIconColor(value);
//                } else if (SQLTreeNodeType.DESCRIPTION.toString().equals(fieldType)) {
//                    node.setDescription(value);
                    }
                }
                lists.add(node);
            }
        }
        return lists;
    }

}
